package cn.stronglink.asset.module.sys.user.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;

import cn.stronglink.asset.model.Permission;
import cn.stronglink.asset.model.User;
import cn.stronglink.asset.module.sys.permission.mapper.PermissionMapper;
import cn.stronglink.asset.module.sys.role.mapper.RoleMapper;
import cn.stronglink.asset.module.sys.user.mapper.UserMapper;
import cn.stronglink.suite.core.config.Resources;
import cn.stronglink.suite.core.exception.BusinessException;
import cn.stronglink.suite.core.util.MD5Encrypt;
import cn.stronglink.suite.core.util.WebUtil;

@Service
@Transactional(rollbackFor=Exception.class) 
public class UserService {
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private PermissionMapper permissionMapper;
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page<User> getUserByParams(Page<User> page,User user){
		page.setRecords(userMapper.getUserByParams(page,user));	
		return page;
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public User login(User user){
		return userMapper.login(user);	
	}

	public void insertUser(User user) {		
		User u = userMapper.getUserByAccount(user.getAccount());
		if(u == null){
			user.setId(IdWorker.getId());
			user.setCreateBy(WebUtil.getCurrentUser());
			user.setCreateTime(new Date());
			user.setPassword(MD5Encrypt.encrypt(user.getPassword()));
			userMapper.insertUser(user);
			roleMapper.insertRoles(user);
		}else{
			throw new BusinessException(Resources.getMessage("USER_EXIST"));
		}	
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public User getUserByAccount(String account) {
		return userMapper.getUserByAccount(account);
	}

	public void removeUser(Long id) {
		userMapper.delUser(id);		
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public User qryUserById(Long id) {
		return userMapper.qryUserById(id);		
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<Long> getUserRoleIds(Long id) {
		return userMapper.getUserRoleIds(id);
	}

	public void updateUser(User user) {
		user.setAccount("");
		if(!StringUtils.isEmpty(user.getPassword())){
			user.setPassword(MD5Encrypt.encrypt(user.getPassword()));
		}
		user.setUpdateTime(new Date());
		user.setUpdateBy(WebUtil.getCurrentUser());
		userMapper.updateUser(user);	
		userMapper.delRoles(user);
		roleMapper.insertRoles(user);
		
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<User> qryAllUser() {
		return userMapper.qryAllUser();
	}

	public void updatePass(Map<String, Object> params) {
		Long userId =WebUtil.getCurrentUser();
		User user = userMapper.qryPassUserById(userId);
		if(!MD5Encrypt.encrypt(params.get("original").toString()).equals(user.getPassword())){
			throw new BusinessException(Resources.getMessage("OLDPASSWORD_IS_INCORRECT"));
		}
		String newPassword = params.get("password").toString().trim();
		String confirmPassword = params.get("reenter").toString().trim();
		if(!newPassword.equals(confirmPassword)){
			throw new BusinessException(Resources.getMessage("NEWPASSWORD_IS_SAME_THE_CONFIRMPASSWORD"));
		}
		
		user.setPassword(MD5Encrypt.encrypt(newPassword));
		userMapper.updatePassword(user);
		
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<String> getSysPermissionByUsername(String account) {
		List<String> list=new ArrayList<String>();
		HashMap<String,Object> map=permissionMapper.getSysPermissionByUsername(account);
		list=getPermission(list,map);
		return list;

	}

	private List<String> getPermission(List<String> list, HashMap<String, Object> map) {
		if(map!=null&&map.get("permission")!=null){
			String permissions=map.get("permission").toString();
			String[] pmss=permissions.split(",");
			if(pmss!=null&&pmss.length>0){
				for(String st:pmss){
					list.add(st);
				}
			}
			List<String> pidList=new ArrayList<String>();
			if(map.get("pid")!=null){
				String pid=map.get("pid").toString();
				String pids[]=pid.split(",");
				if(pids!=null&&pids.length>0){
					for(String st:pids){
						if(!st.equals("-1")&&!pidList.contains(st)){
							pidList.add(st);
						}
					}
				}
			}
			if(pidList.size()>0){
				map=permissionMapper.qryUserPermission(pidList);
				return getPermission(list,map);
			}
		}
		return list;

	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<User> qryUserByDept(Map<String, Object> params) {
		return userMapper.qryUserByDept(params);
	}

}
